package toy.keli.picmap.tools;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.search.core.PoiDetailInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;

import toy.keli.picmap.R;
import toy.keli.picmap.model.def;
import toy.keli.picmap.util.utilGps;

/**
 * 搜索    https://mapopen-pub-androidsdk.cdn.bcebos.com/map/doc/v7.3.0/index.html
 */
public class Search extends  Tools implements  OnGetPoiSearchResultListener{
    // 附近
    // 线路
    PoiSearch mPoiSearch;
    BaiduMap mBaiduMap;
    @Override
    public void bindActivity(Activity a) {
        super.bindActivity(a);
        mBaiduMap = act.mMapView.getMap();
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        initView();
    }

    private void initView() {
        EditText sInput= act.findViewById(R.id.poi);
        Button sButton=act.findViewById(R.id.btn_search);
        //sug 提示
        sInput.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==66 && event.getAction()==1){
                    sButton.callOnClick();
                }
                return false;

            }
        });
        //执行搜索过滤
        sButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                act.searchKey=sInput.getText().toString();
                //图片显示的时候搜索图片否则搜索当前城市
                if(Control.picShowEnable)
                    act.getFilter().runByDate((picModel)->{
                        return picModel.name.matches(".*"+act.searchKey+".*") || picModel.time.matches(".*"+act.searchKey+".*");
                    });
                else
                    citySearch(act.searchKey);
            }
        });
        sButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                boundSearch(act.searchKey);
                return true;
            }
        });
    }

    public  void citySearch(String searchKey) {
        Location.getStatusInfo(mBaiduMap.getMapStatus(),(geoRes)->{
            String cityName=geoRes.getAddressDetail().city;
            mPoiSearch.searchInCity(new PoiCitySearchOption()
                    .city(cityName)
                    .keyword(searchKey)
                    .pageCapacity(200)
                    .pageNum(0)
            );
        });
    }

    public  void boundSearch(String searchKey) {
        LatLngBounds b = mBaiduMap.getMapStatus().bound;
        boundSearch(b,searchKey);
    }
    public  void boundSearch(LatLng a,LatLng b,String searchKey) {
        LatLngBounds searchBounds =new LatLngBounds.Builder()
                .include(a)
                .include(b)
                .build();
        boundSearch(searchBounds,searchKey);
    }
    public  void boundSearch(LatLngBounds b,String searchKey) {
        mPoiSearch.searchInBound(new PoiBoundSearchOption()
                .bound(b)
                .keyword(searchKey));
    }

    public boolean circleSearch(LatLng p,String k){
        return circleSearch(p,k,5000);
    }
    public boolean circleSearch(LatLng p,String k,int r){
        return mPoiSearch.searchNearby(new PoiNearbySearchOption()
                .location(p)
                .keyword(k)
                .pageCapacity(100)
                .radius(r)
        );
    }
    boolean addMarker(LatLng point, int i){
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap)
                .clickable(true).period(i);

        //在地图上添加Marker，并显示
        Marker mMarker = (Marker)mBaiduMap.addOverlay(option);
        return true;
    }
    @Override
    public void onGetPoiResult(PoiResult poiResult) {
            if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                //act.hideMarkers();
                mBaiduMap.clear();
                int i=0;
                for(PoiInfo poi: poiResult.getAllPoi()){
                    addMarker(poi.getLocation(),++i);
                }
            }

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            //marker被点击时回调的方法
            //若响应点击事件，返回true，否则返回false
            //默认返回false
            @Override
            public boolean onMarkerClick(Marker marker) {
                int i=marker.getPeriod();
                //PoiInfo 检索到的第一条信息
                PoiInfo poi = poiResult.getAllPoi().get(i-1);
                //通过第一条检索信息对应的uid发起详细信息检索
                mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                        .poiUids(poi.uid)); // uid的集合，最多可以传入10个uid，多个uid之间用英文逗号分隔。
                return false;
            }
        });
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
        PoiDetailInfo info = poiDetailSearchResult.getPoiDetailInfoList().get(0);
        Button button = new Button(act.getApplicationContext());
        //button.setBackgroundResource(R.drawable.popup);
        button.setText(info.getName()+info.getTelephone());
        InfoWindow mInfoWindow = new InfoWindow(button,info.getLocation(), -100);
        mBaiduMap.showInfoWindow(mInfoWindow);
        //单击步行导航
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                act.onLocationDo((location)->{
                    routeGet(new LatLng(location.getLatitude(),location.getLongitude()),info.getLocation(),"步行");
                });
            }
        });
        //长按信息复制
        button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                act.systemCopy(((Button)v).getText().toString());
                return false;
            }
        });
    }
    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }
    //废弃
    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    public  void routeGet(LatLng startPoint,LatLng endPoint,String title){
        switch (title){
            case "公交":
                RouteParaOption paraOption = new RouteParaOption()
                        .startPoint(startPoint)
                        .endPoint(endPoint)
                        .busStrategyType(RouteParaOption.EBusStrategyType.bus_recommend_way);
                //调起百度地图
                try {
                    BaiduMapRoutePlan.openBaiduMapTransitRoute(paraOption, act);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                BaiduMapRoutePlan.finish(act);
                break;
            case "步行":
                //构建导航参数
                NaviParaOption para = new NaviParaOption()
                        .startPoint(startPoint)
                        .endPoint(endPoint);
                //调起百度地图
                try {
                    BaiduMapNavigation.openBaiduMapWalkNavi(para, act);
                } catch (BaiduMapAppNotSupportNaviException e) {
                    e.printStackTrace();
                    //调起失败的处理
                }
                //调起结束时及时调用finish方法以释放相关资源
                BaiduMapNavigation.finish(act);
                break;
        }
    }


    public void openPointMenu(View v, LatLng point){
        //Android menu 简单创建  https://www.cnblogs.com/llxbl/p/6045042.html
        PopupMenu pm = new PopupMenu(act,v);
        Menu menu = pm.getMenu();
        //多行字符串的编辑问题  https://blog.csdn.net/jiuwuerliu/article/details/51207045
        String tree = "周边\n\t美食\n\t公交站牌\n\t酒店\n\t银行\n\t超市\n\t医院\n\t厕所\n\t公园\n\t书店\n\t更多\n"+
                "到这里去\n\t公交\n\t步行\n"+
                "地图打开";
        addCMenu(menu,new def.tree(tree),0);

        pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String title = String.valueOf(item.getTitle());
                if(!item.hasSubMenu())
                    switch (item.getGroupId()){
                        case 1:     //周边
                            if(title.equals("更多")){
                                act.msg("待开发");
                                return false;
                            }
                            circleSearch(point,title);
                            break;
                        case 2:     //到这里去
                            //定义起终点坐标（天安门和百度大厦）

                            act.onLocationDo((location)->{
                                routeGet(new LatLng(location.getLatitude(),location.getLongitude()),point,title);
                            });

                            break;
                        case 3:     //从这里出发

                        case 4:     //百度打开
//                        openApp("","",(obj)->{
//
//                        });
                            //常用协议打开  http://www.voidcn.com/article/p-ebthoola-bdx.html
                            double[] a = utilGps.bd2wgs.call(point.latitude, point.longitude);
                            Uri uri = Uri.parse("geo:"+a[0]+","+a[1]);
                            Intent it = new Intent(Intent.ACTION_VIEW,uri);
                            act.startActivity(it);
                            break;
                        case 5:     //固定中心点
                            break;
                    }
                return true;
            }
        });
        pm.show();
    }
    private void addCMenu(Menu menu, def menuData, int gid) {
        int id=0,pid=0;
        for(def key: menuData){
            pid=(gid==0)? id+1:gid;
            def cMenuData=menuData.get(key);
            if(cMenuData.size()<=0)
                menu.add(pid,id,0,key.toString());
            else {
                SubMenu cMenu = menu.addSubMenu(pid, id, 0, key.toString());
                addCMenu(cMenu,cMenuData,pid);
            }
            id++;
        }
    }
}


